package org.kassa.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.kassa.model.Item;
import org.kassa.model.Selling;

public class SellingDaoImpl implements SellingDao {
	
        @Override
	public boolean sellItem(Item item){
            try {
                String sql = "UPDATE items SET quantity = quantity - ? WHERE id = ?";
                PreparedStatement ps = DaoHelperImpl.getPreparedStatement(sql);
                ps.setInt(1, item.getQuantity());
                ps.setInt(2, item.getId());
                if (ps.executeUpdate() == 1) {
                        if (registerSelling(new Selling(item)))	return true;
                }
            } catch (SQLException e) {
                org.kassa.service.Logger.log("SQLException caught");
                e.printStackTrace();
            }
            return false;
	}
        
        @Override
        public boolean checkQuantity(Item item) {
            try {
                String sql = "SELECT quantity FROM items WHERE code = ?";
                PreparedStatement ps = DaoHelperImpl.getPreparedStatement(sql);
                ps.setInt(1, item.getCode());
                ResultSet rs = ps.executeQuery();
                if (rs.next()) { 
                    if((rs.getInt("quantity") - item.getQuantity()) >= 0) {
                        return true;
                    }  
                }
            } catch (SQLException e) {
                org.kassa.service.Logger.log("SQLException caught");
                e.printStackTrace();
            }
            return false;
        }
	
	private boolean registerSelling(Selling selling){
            try {
                Item item = selling.getItem();
                String sql = "INSERT INTO sellings (itemid, itemname, quantity, date, price) VALUES (?, ?, ?, ?, ?)";
                PreparedStatement ps = DaoHelperImpl.getPreparedStatement(sql);
                ps.setInt(1, item.getId());
                ps.setString(2, item.getName());
                ps.setInt(3, item.getQuantity());
                ps.setTimestamp(4, selling.getDate());
                ps.setDouble(5, item.getPrice());
                if (ps.executeUpdate() == 1) return true;
            } catch (SQLException e) {
                org.kassa.service.Logger.log("SQLException caught");
                e.printStackTrace();
            }
        return false;
	}
	
}
